import CreatorModule.CreatorPOA;
import org.omg.CORBA.ORB;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 实现用户管理creator.idl中定义的接口
 */
public class CreatorImpl extends CreatorPOA {
    private Map<String,Person> personMap;
    private String name=null;
    private ORB orb;
    private ToDoListServer toDoListServer;
    private UserImpl userImpl;

    public CreatorImpl(){
        init();
    }

    /**
     *初始化
     */
    private void init(){
        //从文件中读取用户列表并转化为HashMap
        try {
            FileInputStream fin=new FileInputStream("person.file");
            ObjectInputStream oin=new ObjectInputStream(fin);
            try {
                Object object=oin.readObject();
                personMap=(HashMap<String,Person>)object;
            }catch (ClassNotFoundException e){
                System.out.println("object cast error");
                personMap=new HashMap<String,Person>();
            }
            oin.close();
            fin.close();
        }catch (Exception e){
            personMap=new HashMap<String,Person>();
        }
    }

    /**
     * 将用户表保存到本地
     */
    private void saveDate(){
        try{
            FileOutputStream fout=new FileOutputStream("person.file");
            ObjectOutputStream oout=new ObjectOutputStream(fout);
            oout.writeObject(personMap);
            oout.flush();
            fout.flush();
            oout.close();
            fout.close();
        }catch (Exception e){
            System.out.println("save error.");
            e.printStackTrace();
        }
    }

    public void setOrb(ORB orb){
        this.orb=orb;
    }

    public void setToDoListServer(ToDoListServer toDoListServer){
        this.toDoListServer=toDoListServer;
    }

    /**
     * 对用户名进行注册服务
     * @param name
     */
    private void registerService(String name){
        toDoListServer.registerUserName(name);
    }

    @Override
    public boolean login(String name,String password){
        Person p=personMap.get(name);
        if(p!=null&&p.getPassword().equals(password)){
            this.name=name;
            //登录成功后对用户名进行注册
            registerService(name);
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean register(String name,String password){
        Person p=personMap.get(name);
        if(p!=null){            //表示用户名已存在
            return false;
        }else {
            personMap.put(name,new Person(name,password));
            saveDate();
            return true;
        }
    }











}
